package com.sinosoft.dsp.builder.mojo;

import java.io.File;
import java.util.Map;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.velocity.VelocityComponent;

import com.sinosoft.builder.config.BuilderConfig;
import com.sinosoft.builder.config.ILoaderHolder;
import com.sinosoft.builder.config.MavenLogger;
import com.sinosoft.builder.config.ParsingException;
import com.sinosoft.builder.generator.GeneratorException;
import com.sinosoft.builder.parser.SinoParserType;
import com.sinosoft.dsp.builder.generator.BusinessConceptEntityBeanGenerator;

/**
 * Maven插件的Mojo类，通过配置文件生成entity bean
 * 
 * @author 潘巍（Peter Pan）
 * @since 2010-12-9 上午10:14:20
 * 
 * @goal gen
 * @phase generate-sources
 * @requiresDependencyResolution test
 */
public class EntityMojo extends AbstractMojo {

	/**
	 * The Maven project.
	 * 
	 * @parameter expression="${project}"
	 * @required
	 * @readonly
	 */
	private MavenProject project;

	/**
	 * 生成实体文件目录
	 * 
	 * @parameter expression="${dest}"
	 *            default-value="${project.build.directory}/generated"
	 */
	protected File destDir;

	/**
	 * 模板目录
	 * 
	 * @parameter expression="${basedir}/src/main/resources/META-INF/templates"
	 */
	protected File tempDir;

	/**
	 * 资源文件目录
	 * 
	 * @parameter expression="${res}"
	 *            default-value="${basedir}/src/main/resources"
	 */
	protected File resDir;

	/**
	 * 业务概念配置
	 * 
	 * @parameter
	 */
	protected Map businessConceptConfig;

	/**
	 * @component
	 */
	protected VelocityComponent velocity;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		MavenLogger logger = new MavenLogger(getLog());
		try {
			// 1.创建业务概念文件加载器，加载XML配置文件
			ILoaderHolder bcLoader = new BuilderConfig(Thread.currentThread()
					.getContextClassLoader(), logger, destDir, resDir,
					velocity, SinoParserType.BUSSINESSCONCEPT);

			// 创建文件业务概念的文件生成器，并创建文件
			BusinessConceptEntityBeanGenerator generator = new BusinessConceptEntityBeanGenerator(
					bcLoader, businessConceptConfig, logger);
			generator.createFiles();

			project.addCompileSourceRoot(destDir.getAbsolutePath());

		} catch (GeneratorException e) {
			getLog().error("执行创建实体时出现错误！");
			getLog().error(e);
		} catch (ParsingException e) {
			getLog().error("执行创建实体的初始化时出现错误！");
			getLog().error(e);
		}
	}

}
